package minesweeper;

import javax.sound.sampled.*;
import java.io.InputStream;

public class SoundManager {
    private Clip clickSound;
    private Clip flagSound;
    private Clip explosionSound;

    public SoundManager() {
        loadSounds();
    }

    private void loadSounds() {
        clickSound = loadClip("/resources/music/click.wav");
        flagSound = loadClip("/resources/music/flag.wav");
        explosionSound = loadClip("/resources/music/explosion.wav");
    }

    private Clip loadClip(String path) {
        try (InputStream is = getClass().getResourceAsStream(path)) {
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(is);
            Clip clip = AudioSystem.getClip();
            clip.open(audioIn);
            return clip;
        } catch (Exception e) {
            System.err.println("Error loading sound: " + path);
            e.printStackTrace();
        }
        return null;
    }

    public void playClick() {
        playSound(clickSound);
    }

    public void playFlag() {
        playSound(flagSound);
    }

    public void playExplosion() {
        playSound(explosionSound);
    }

    private void playSound(Clip clip) {
        if (clip != null) {
            new Thread(() -> {
                clip.setFramePosition(0);
                clip.start();
            }).start();
        }
    }
}